<?php

namespace App\Models\Member;

use App\Models\BaseModel;
use App\Models\Member\PostageZto;
use App\Models\Member\PostageEms;
use App\Models\Member\User;
use App\Models\Member\Grade;
use App\Models\Member\Share;
use App\Models\Member\TeamAward;
use App\Common\PayHandler;
use App\Models\Member\OrderItem;
use App\Models\Member\Good;
use Illuminate\Support\Facades\Hash;
use App\Common\AliossHandler;
use Auth;
use Config;

class Order extends BaseModel
{
    protected $fillable = [
        'id', 'store_id', 'user_id', 'order_code', 'pay_user_id',
        'order_status', 'type', 'accepter_name', 'accepter_phone', 
        'province_name', 'city_name', 'district_name', 'detail_address', 
        'national_code', 'express_type',
        'express_weight', 'express_price', 'express_number', 'base_price', 'cost_price',
        'pay_price', 'jf_price', 'jf', 'express_at', 
        'cancel_at', 'pay_at', 'send_at', 'accept_at', 
        'created_at', 'updated_at'
    ];
    // 获取指定id的订单信息
    public function getOrder($id)
    {
        $order = $this->where('id', $id)->first();
        if ($order->order_status == 2) {
            $seconds = time() - strtotime($order->created_at);
            $order->has_time = $seconds > 1800 ? 0 : (1800 - $seconds) * 1000;
        }
        return $order;
    }
    // 得出订单信息 - 用户信息 / 预设的订单信息
    public function setOrder($user, $orderInfo)
    {
        $order = [];
        $order['user_id'] = $user['id'];
        $order['store_id'] = $user['store_id'];
        $order['order_code'] = genericOrderCode($user['id']);
        $order['pay_user_id'] = $user['id'];
        $order['order_status'] = 2;
        $order['type'] = empty($orderInfo['type']) ? $orderInfo['type'] : 1;// 会员订单
        $order['express_type'] = empty($orderInfo['express_type']) ? $orderInfo['express_type'] : 'ZTO';
        $order['express_weight'] = $orderInfo['express_weight'];
        $order['express_price'] = 0;
        $order['base_price'] = $orderInfo['base_price'];
        $order['cost_price'] = $orderInfo['cost_price'];
        $order['pay_price'] = $orderInfo['pay_price'];
        $order['jf_price'] = $orderInfo['jf_price'];// 抵扣数额
        $order['jf'] = $orderInfo['jf'];
        $order['created_at'] = date('Y-m-d H:i:s');
        $order['express_at'] = date('Y-m-d H:i:s', strtotime("+30 min"));
        $orderId = $this->insertGetId($order);
        return $orderId;
    }
    // 获取指定用户未付款订单 - 用户ID 
    public function getNotPayOrder($id)
    {
        return $this->where('user_id', $id)->where('order_status', 2)->first();
    }
    public function getMemOrderTips($order_status)
    {
        $tips = [];
        switch ($order_status) {
            case 0:
                $tips['left'] = '超时取消';
                $tips['right'] = '会员订单';
                break;
            case 1:
                $tips['left'] = '已取消';
                $tips['right'] = '会员订单';
                break;
            case 2:
                $tips['left'] = '倒计时计算中';
                $tips['right'] = '会员订单';
                break;
            case 3:
                $tips['left'] = '马上为您发货';
                $tips['right'] = '会员订单';
                break;
            case 4:
                $tips['left'] = '您的快递已发出';
                $tips['right'] = '会员订单';
                break;
            case 5:
                $tips['left'] = '已收货';
                $tips['right'] = '会员订单';
                break;         
            default:
                $tips['left'] = '未知状态';
                $tips['right'] = '会员订单';
                break;
        }
        return $tips;
    }

    // 通过订单id 取消会员订单
    public function cancelMemOrder($id)
    {
        $cancel = $this->where('id', $id)->where('type', 1)->update(['order_status' => 1, 'cancel_at' => date('Y-m-d H:i:s')]);
        if ($cancel) {
            return $this->successClient($id, '会员订单取消成功!'); 
        } else {
            return $this->errorClient($id, '会员订单取消失败!'); 
        }
    }
    
    // 收货
    public function accepterMemOrder($id)
    {
        $accepter = $this->where('id', $id)->where('type', 1)->update(['order_status' => 5, 'accept_at' => date('Y-m-d H:i:s')]);
        if ($accepter) {
            return $this->successClient($id, '会员订单取消成功!'); 
        } else {
            return $this->errorClient($id, '会员订单取消失败!'); 
        }
    }

    // 验证订单信息 , 获取邮费 , 更新订单信息 - 1 更新地址 / 2 更新发货 / 3 更新积分
    public function updateMemOrder($info, $type = 1)
    {
        $orderId = $info['id'];// ###
        $order = $this->getOrder($orderId);
        if (empty($order)) {
            return $this->errorClient('', '订单不存在');
        }
        if ($order['order_status'] != 2) {
            return $this->errorClient($order['order_status'], '这不是待付款订单, 无法修改地址信息!');
        }
        $weightArr = json_decode($order['express_weight'], 1);
        $storeId = $order['store_id'];
        if ($type == 1) {
            $info['express_type'] = $order['express_type'];
            $expressPrice = $this->getExp($info['express_type'], $info['national_code'], $weightArr, $storeId);
            if ($expressPrice['code'] != 20000) {
                return $expressPrice;
            }
            $expressPrice = $expressPrice['data'];
            $info['express_price'] = $expressPrice;
            return $this->updateAccepter($info);
        } elseif ($type == 2) {
            $info['express_type'] = $info['express_type'];
            $expressPrice = $this->getExp($info['express_type'], $info['national_code'], $weightArr, $storeId);
            if ($expressPrice['code'] != 20000) {
                return $expressPrice;
            }
            $expressPrice = $expressPrice['data'];
            $info['express_price'] = $expressPrice;
            return $this->updateExpressType($info);
        } else {
            return $this->updateJf($info);
        }
    }
    public function updateAccepter($info)
    {
        $orderInfo = [];
        $orederInfo['accepter_name'] = $info['accepter_name'];
        $orederInfo['accepter_phone'] = $info['accepter_phone'];
        $orederInfo['province_name'] = $info['province_name'];
        $orederInfo['city_name'] = $info['city_name'];
        $orederInfo['district_name'] = $info['district_name'];
        $orederInfo['detail_address'] = $info['detail_address'];
        $orederInfo['national_code'] = $info['national_code'];
        $orederInfo['express_price'] = $info['express_price'];
        $updateAccepter = $this->where('id', $info['id'])->update($orederInfo);
        if ($updateAccepter) {
            return $this->successClient($info['express_price'], '地址信息更新成功!'); 
        } else {
            return $this->errorClient($info['express_price'], '地址信息更新失败!'); 
        }
    }
    public function updateExpressType($info)
    {
        $orderInfo = [];
        $orederInfo['express_type'] = $info['express_type'];
        $orederInfo['express_price'] = $info['express_price'];
        $updateAccepter = $this->where('id', $info['id'])->update($orederInfo);
        if ($updateAccepter) {
            return $this->successClient($info['express_price'], '发货方式更新成功!'); 
        } else {
            return $this->errorClient($info['express_price'], '发货方式更新失败!'); 
        }
    }
    public function updateJf($info)
    {
        $orderInfo = [];
        $orederInfo['jf_price'] = $info['jf_price'];
        $updateAccepter = $this->where('id', $info['id'])->update($orederInfo);
        if ($updateAccepter) {
            return $this->successClient($info['jf_price'], '积分更新成功!'); 
        } else {
            return $this->errorClient($info['jf_price'], '积分更新失败!'); 
        }
    }
    public function getExp($expressType, $nationalCode, $weightArr, $storeId)
    {
        switch ($expressType) {
            case 'ZTO':
                $PostageZto = new PostageZto;
                $exp = $PostageZto->expZto($nationalCode, $weightArr, $storeId);
                break;
             case 'EMS':
                $PostageEms = new PostageEms;
                $exp = $PostageEms->expEms($nationalCode, $weightArr, $storeId);
                break;
            default:
                break;
        }
        return $exp;// 返回 是否成功以及 邮费金额
    }

    // 会员订单支付前验证 - 支付类型 / 订单ID / 支付密码(默认为空非余额支付不使用)
    public function checkMemPay($type, $orderId, $passwordPay = 0)
    {
        // 判断订单是否存在
        $order = $this->getOrder($orderId);
        if (empty($order)) {
            return $this->errorClient('', '订单不存在');
        }
        if ($order['order_status'] != 2) {
            return $this->errorClient($order['order_status'], '这不是待付款订单, 无法支付!');
        }
        if (empty($order['accepter_phone']) || empty($order['national_code']) || empty($order['express_type'])) {
            return $this->errorClient('', '订单地址信息不完整, 无法支付!');
        }
        $orderitem = OrderItem::where('order_id',$orderId)->get()->toArray();
        $goodIds = array_column($orderitem,'good_id');
        $goodInfo = Good::whereIn('id',$goodIds)->whereIn('status',[2,3])->get()->toArray();
        if(!empty($goodInfo)){
            return $this->errorClient('', '该订单中存在下架商品，请取消该订单重新下单！'); 
        }
        if($type == 0){
            return $this->successClient('', '会员订单支付前验证无误'); 
        }
        $userInfo = User::where('id', $order['user_id'])->first()->toArray();
        if ($type == 1) {
            if (!Hash::check($passwordPay, $userInfo['password_pay'])) {
                return $this->errorClient('', '支付密码错误, 请重试!');
            }
            // 余额是否足够 / 积分是否足够
            if ($userInfo['gold'] < $order['pay_price'] - $order['jf_price']) {
                return $this->errorClient('', '余额不足!');
            }
            if ($userInfo['jf'] < $order['jf_price']) {
                return $this->errorClient('', '积分不足, 请修改积分使用数目!');
            }
        }
        // 准备信息
        $info = $this->planInfo($type, $order, $userInfo, $passwordPay);
        return $info;
    }
    // 准备支付信息 - 支付类型 / 订单信息 / 下单人信息
    public function planInfo($type, $order, $userInfo, $passwordPay)
    {
        $Grade = new Grade;
        $Share = new Share;
        $TeamAward = new TeamAward;
        $memGrades = $Grade->storeGrade($order['store_id']);
        $memShares = $Share->storeShare($order['store_id']);
        $memTeamAwards = $TeamAward->storeTeamAward($order['store_id']);
        
        $info = [];// 用户信息 / 订单信息 / 会员升级信息 / 会员分享奖金信息 / 团队奖励信息
        $info['order'] = $order;
        $info['userInfo'] = $userInfo;
        $info['grade'] = $memGrades;
        $info['share'] = $memShares;
        $info['teamAward'] = $memTeamAwards;
        // if ($type == 1) {
            return PayHandler::payMemOrder($info, $type, $passwordPay);
        // } else {
            // 微信支付 逻辑
        // }
    }

    // 会员订单更新 - 支付时间 / 订单状态
    public function updateMemPay($id)
    {
        $orderInfo = [];
        $orederInfo['order_status'] = 3;
        $orederInfo['pay_at'] = date('Y-m-d H:i:s');
        $updateMemPay = $this->where('id', $id)->update($orederInfo);
        if ($updateMemPay) {
            return $this->successClient('', '会员订单支付更新完成!'); 
        } else {
            return $this->errorClient('', '会员订单支付更新完成!'); 
        }
    }

    public function getList($request)
    {
        $user = Auth::user()->toArray();
        $status = $request['status'];
        $sql = $this->where('user_id', $user['id']);
        if($status != "all"){
            $sql->where('order_status', $status);
        }
        $data = $sql->orderBy('created_at', 'desc')->paginate(10)->toArray();
        foreach ($data['data'] as $key => $item) {
            $orderItem = new OrderItem;
            $data['data'][$key]['order_item'] = $orderItem->getOrderItem($item['id']);
            $data['data'][$key]['order_status_cn'] = Config::get('const.order_status_str')[$item['order_status']];
            foreach ($data['data'][$key]['order_item'] as $index => $value) {
                $data['data'][$key]['order_item'][$index]['good_logo'] = AliossHandler::read('good', $value['good_logo']);
            }
        }

        return $this->successClient($data);
    }

    // 获取用户历史会员订单零售价总和
    public function getAllPrice($id)
    {
        return $this->where('user_id', $id)->where('type', 1)->whereIn('order_status', [3,4,5])->sum('base_price');
    }

    //  获取用户的团队销售额
    public function teamSales($user){
        $userIds = User::where('left', '>=', $user['left'])->where('right', '<=', $user['right'])->where('team_id', $user['id'])->select('id')->get()->toArray();
        $ids = array_column($userIds,'id');
        return $this->where('type',1)->whereIn('user_id',$ids)->whereIn('order_status', [3,4,5])->sum('base_price');
    }
}
